<?php 
class Albums extends Model_Abstract
{
	public $tableName = 'pm_albums';
	
	protected $_validation = array(
		'name' => array(
			array('max_length', '图片名称长度不能超过100', 100),
			array('not_empty', '请填写图片名称')
		),
		'foldername' => array(
			array('not_empty', '请填相册存储文件夹的名称')
		),
		'sketch' => array(
			array('max_length', '请在500个字以内描述相册简介', 500),
		),
	);
	
	public function init()
	{
		$this->initAttributes();
	}
	
	public function initAttributes()
	{
		$this->attributes = array(
			'name' =>'',
			'name_en' => '',
			'foldername' => '',
			'parent_id' => 0
		);
	}
	
	public static function model($classname = __CLASS__)
	{
		return parent::model($classname);
	}
	
	public function attributeLabels()
	{
		return array(
			'name' => '相册名'
		);
	}
	
	protected function _find($fields = '*', $attributes = array(), $constraint = array(), $conditions = array(), $params = array())
	{
		$c = array_merge(
			$this->_constraintFind,
			array('zTreeSetting' => false, 'getCoverPicture' => false, 'getCoverPictureFilePath' => true),
			$constraint
		);
		extract($c);
		if($getCoverPicture){				
			//如果要获取相册封面，则查询结果会始终包含id， 并且束项中的setResultKey始终设为id，stripName设为false，onlyOne始终设为fasle
			if(!is_array($fields)){
				$fields = array($fields);
			}
			if(!in_array('id', $fields)){
				$fields[] = 'id';
			}
			
			$constraint['setResultKey'] = 'id';
			$constraint['stripName'] = false;
			$constraint['onlyOne'] = false;
		}
		
		$result = parent::_find($fields, $attributes, $constraint, $conditions, $params);
		
		if($getCoverPicture){
			if(!empty($result)){
				$ids = array_keys($result);
				$coverPics = Pictures::model()->find('*', array('albumid' => $ids), array('groupBy' => 'albumid', 'getFilePath' => $getCoverPictureFilePath));
			}
			if(!empty($coverPics)){
				foreach($coverPics as $pic){
					$result[$pic['albumid']]['coverPicture'] = $pic;
				}
			}
		}
		
		if(is_array($zTreeSetting) && !empty($zTreeSetting)){
			foreach($result as $k => $v){
				$result[$k] = array_merge($v, $zTreeSetting);
			}
		}
		
		return $result;
	}
	
	protected function _delete($attributes = array(), $conditions = array(), $params = array())
	{
		$deletedItems = $this->find('*', $attributes, array(), $conditions, $params);
		$this->_before_sql();
		$this->_filterAttributesScriptTags();
		if(parent::_delete($attributes, $conditions, $params)){
			$albumAllSimple = array_merge(
				$this->find(),
				$deletedItems
			);
			foreach($deletedItems as $k => $item){
				$albumFolder = $this->getFolderPath(array('data' => $item), $albumAllSimple);
				Util::delete_directory(
					$albumFolder['sysPath']
				);
			}
				
			return true;
		}else{
			return false;
		}
	}
	
	protected function _attributesIdentity($names = array(), $limitCount = 0, $exceptSelf = false)
	{
		$ret = true;
		$otherNodesUnderParent = $this->find('*', array('parent_id' => $this->attributes['parent_id']),  array('setResultKey' => 'id'));
		if(!empty($this->attributes['id'])){
			unset($otherNodesUnderParent[$this->attributes['id']]);
		}
		if(!empty($otherNodesUnderParent)){
			$attrNames = array();
			$attrFoldernames = array();
			foreach($otherNodesUnderParent as $id => $node){
				$attrNames[] = $node['name'];
				$attrFoldernames[] = $node['foldername'];
			}
			
			if(in_array($this->attributes['name'], $attrNames)){
				$this->_validationError['name'][] = 'name在同级目录中重复';
				$ret = false;
			}
			if(in_array($this->attributes['foldername'], $attrFoldernames)){
				$this->_validationError['foldername'][] = 'foldername在同级目录中重复';
				$ret = false;
			}
		}
		
		return $ret;
	}
	
	protected function _save($validate = true)
	{
		if(!empty($this->attributes[$this->primaryKey])){
			$oldFoldername = $this->find('foldername', array('id' => $this->attributes[$this->primaryKey]), array('onlyOne' => true, 'stripName' => true));
			if($this->attributes['foldername'] != $oldFoldername){
				$oldFolderPath = $this->getFolderPath(array('id' => $this->attributes[$this->primaryKey]));
			}
		}
		
    	$this->_before_sql();
		$this->_filterAttributesScriptTags();
		if(parent::_save()){
			if(!empty($this->attributes[$this->primaryKey])){
				if($this->attributes['foldername'] != $oldFoldername){
					$oldSysPath = $oldFolderPath['sysPath'];
					
					$newSysPath = rtrim($oldSysPath, '/');
					$newSysPath = rtrim($newSysPath, $oldFoldername);
					$newSysPath .= $this->attributes['foldername'];
					$renameResult = rename($oldSysPath, $newSysPath);
					if(!$renameResult){			//如果重命名文件夹没有成功，将已更新的foldername字段改回旧的值
						$this->update(array('foldername' => $oldFoldername), array('id' => $this->attributes[$this->primaryKey]));
						$this->attributes['foldername'] = $oldFoldername;
					}
				}
			}
			
			return true;
		}else{
			return false;
		}
	}
	
	public function getFolderPath($albumGet = array('id' => null, 'data' => null), $albumAllSimple = null)
	{
		if($albumAllSimple === null){
			$albumAllSimple = $this->find();
		}
		if(empty($albumAllSimple)){
			return null;
		}
		$albumAllSimple = $this->setResultKey($albumAllSimple, 'id');
		
		if(!empty($albumGet['data'])){
			$album = $albumGet['data'];
		}else if(!empty($albumGet['id'])){
			$album = $albumAllSimple[$albumGet['id']];
		}
		if(empty($album)){
			return null;
		}

		
		$parentId = $album['parent_id'];
		$parentIds = array();
		while($parentId){
			$parentIds[] = $parentId;
			$parentId = $albumAllSimple[$parentId]['parent_id'];
		}
		
		$path = '/';
		if(!empty($parentIds)){
			$parentIds = array_reverse($parentIds);
			foreach($parentIds as $id){
				$path .= $albumAllSimple[$id]['foldername'] . '/';
			}
		}
		$path .= $album['foldername'] . '/';
		return array(
			'sysPath' => PICMATERIAL_DIR . $path,
			'relativePath' => $path
		);
	}
	
	protected function arrayToTree($arr, $p_id = 0)
	{
		$tree = array();
		foreach($arr as $row){
			if($row['parent_id'] == $p_id){
				$row['children'] = $this->arrayToTree($arr, $row['id']);				
				$tree[] = $row;
			}
		}
		return $tree;
	}
	
	public function getTree($allAlbums = null)
	{
		/*$constrain = array(
			//'orderBy' => array('fields' => 'id', 'seq' => 'ASC')
		);*/
		if($allAlbums == null){
			$allAlbums = $this->find(/*'*', null, $constrain*/);
		}
		return $this->arrayToTree($allAlbums);  
	}
	
	public function getEveryBranchOfTree($tree, &$rows=array(), $id=0) {
	    foreach($tree as $v) {
	        if(isset($v['children']) and is_array($v['children'])) {
	            $this->getEveryBranchOfTree($v['children'], $rows, $v['id']);
	        }
	        $rows[$v['id']] = $v;
	    }
	    ksort($rows);
	    return $rows;
	}
	
	public function getBranchOfNode($albumsTreeWithEveryBranch, $nodeId)
	{
	    $rows = array();
	    foreach($albumsTreeWithEveryBranch as $v) {
	        if($v['parent_id'] == $nodeId) {
	            unset($v['parent_id']);
	            $rows[] = $v;
	        }
	    }
	    return $rows;
	}
	
	public function getTrunkOfNode($albumAllSimple, $nodeId, $retFormat = 'tree')
	{
		$albumAllSimple = $this->setResultKey($albumAllSimple, 'id');
		$pid = $albumAllSimple[$nodeId]['parent_id'];
		$trunk = array();
		while($pid > 0){
			$parentNode = $albumAllSimple[$pid];
			if($retFormat == 'tree'){
				if(!empty($trunk)){
					$parentNode['children'] = $trunk;
				}
				$trunk = $parentNode;
			}else if($retFormat = 'justArray'){
				array_unshift($trunk, $parentNode);
			}
			$pid = $albumAllSimple[$pid]['parent_id'];
		}
		
		return $trunk;
	}
	
	public function getIdsUnderId($albumAllSimple, $id)
	{
		$idsOnBranch = array($id);
		foreach($albumAllSimple as $k => $album){
			if(in_array($album['parent_id'], $idsOnBranch)){
				$idsOnBranch[] = $album['id'];
			}
		}
		
		return $idsOnBranch;
	}
	
	public function deleteByIdWithBranch($id)
	{
		$albumAllSimple = Albums::model()->find();
		$deleteIds = $this->getIdsUnderId($albumAllSimple, $id);
		
		//step1
		$deletePicsResult = Pictures::model()->delete(array('albumid' => $deleteIds));
		//step2
		$deleteAlbumsResult = $this->delete(array('id' => $deleteIds));

		return $deleteAlbumsResult && $deletePicsResult;
	}
}








